package android.javaClasses;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.SocketException;
import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: michelle
 * Date: 4/25/11
 * Time: 1:35 PM
 * To change this template use File | Settings | File Templates.
 */
public class Receiver {
    private ArrayList<Stream> socketStreams = new ArrayList<Stream>();
    private OnNewSocketStreamListener listener;
    private ServerSocket server;
    private Thread thread;
    private int port;
    private boolean running;

    public static interface OnNewSocketStreamListener {
        void onNewSocket(Stream stream);
    }

    public Receiver(int port, OnNewSocketStreamListener listener) {
        this.listener = listener;
        this.port = port;
    }

    /**
     * Starts a new thread which listens for incoming connections and accepts them.
     * Adds the accepted sockets to an ArrayList
     */
    public synchronized void start() {
        if(thread != null) return;
        try {
            server = new ServerSocket(port);
        } catch (IOException e) {
            e.printStackTrace();
        }
        thread = new Thread (new Runnable() {
            @Override
            public void run() {
                try {
                    running = true;
                    while(running) {
                        Stream newStream = new Stream(server.accept());
                        listener.onNewSocket(newStream);
                        socketStreams.add(newStream);
                    }
                } catch (SocketException e) {
                    //Stop has been called
                    e.printStackTrace();
                } catch (IOException e) {
                    //error handling
                    e.printStackTrace();
                }
            }
        });
        thread.start();

    }

    public ArrayList<Stream> getSocketStreams() {
        return socketStreams;
    }

    /**
     * Stops the thread which runs in the start() method.
     * Closes all streams and the server.
     */
    public synchronized void stop() {
        if(thread == null) return;
        running = false;
        try {
            if(server != null) {
                server.close();
            }
        } catch (IOException e) {}
        for (Stream stream : socketStreams) {
            stream.close();
        }
        socketStreams.clear();
        thread = null;
    }

}
